from rest_framework import serializers
from .models import User
import re
from .models import Address
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_verify_email


'''用户注册的序列化类'''


class CreateUserSerializer(serializers.ModelSerializer):
    '''
    注册的序列化器
    序列化的时候需要校验的字段
    序列化的所有字段[id,username,password,password2,mobile,sms_code,allow]
    需要校验的字段['username', 'password', 'password2', 'mobile', 'sms_code', 'allow']
    模型中已存在的字段['id', 'username', 'password', 'mobile']
    需要序列化的字段['id', 'username', 'mobile', 'token']
    需要反序列化的字段['username', 'password', 'password2', 'mobile', 'sms_code', 'allow']
    添加模型中没有的字段
    '''
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', 'token']
        extra_kwargs = {  # 修改字段选项
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {  # 自定义校验出错后的错误信息提示
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码'
                }
            }
        }

    def validate_mobile(self, value):
        '''单独校验手机号码'''
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号码格式不正确!')
        return value

    def validate_allow(self, value):
        '''是否同意协议'''
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, attrs):
        '''校验两次密码是否相同
        attrs前端传过来的所有的数据,是一个字典
        '''
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次输入的密码不一致')

        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        # 向redis数据库存储的时间都是以字符串存储的,取出来都是bytes,需要转码
        if real_sms_code is None or attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('验证码错误')
        return attrs

    def create(self, validated_data):
        # 把不需要存储的 password2, sms_code, allow 从字段中移除
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        # 把密码先取出来,字典的pop方法是删除对用的字典键值,但是返回值是字典的删除的值
        password = validated_data.pop('password')
        # 创建用户模型对象,给模型中username和mobile属性赋值
        user = User(**validated_data)
        user.set_password(password)  # 把密码加密后再赋值给user的password属性
        user.save()  # 存储到数据库

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 引用jwt中的叫jwt_payload_handler函数(生成payload)
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 函数引用 生成jwt

        payload = jwt_payload_handler(user)  # 根据user生成用户相关的载荷
        token = jwt_encode_handler(payload)  # 传入载荷生成完整的jwt

        user.token = token

        return user


'''获取单一用户信息的序列化类'''


class UserDetailSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


'''更新用户邮箱的序列化器'''


class EmailSerializers(serializers.ModelSerializer):

    class Meta:
        #指定序列化的模型
        model = User
        #指定序列化的字段
        fields =['id','email']
        #因为前段有可能不传递数据,这样后端如果不设置该字段的require属性,就会保存为空,设置之后就会报错.
        extra_kwargs={
            'email':{
                'required':True
            }
        }

    def update(self, instance, validated_data):
        '''
        可以不书写该方法也是可以执行的,但是为了发送邮件方便所以就重写了该方法
        :param instance: 要更改的user模型对象
        :param validated_data: 验证后的数据
        :return: 返回instance
        '''
        instance.email = validated_data.get('email')
        instance.save()
        verify_url = instance.generate_email_verify_url
        send_verify_email.delay(instance.email,verify_url)
        return instance

class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')

        return value

    def create(self, validated_data):
        user = self.context['request'].user  # 获取用户模型对象
        validated_data['user'] = user  # 将用户模型保存到字典中
        return Address.objects.create(**validated_data)

class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)